var express = require('express')
var router = express.Router()
const loginCheck = require('../middleware/loginCheck')
const {
  getList,
  getDetail,
  newBlog,
  updateBlog,
  delBlog,
} = require('../controller/blog')
const { SuccessModel, ErrorModel } = require('../module/resModel')

/* GET users listing. */

// 列表
router.get('/list', loginCheck, async function (req, res, next) {
  const res2 = await getList(req.query)
  res.json(new SuccessModel(res2))
})

// 详情
router.get('/detail', loginCheck, async function (req, res, next) {
  const id = req.query.id
  console.log(id, '--- id 24 ---')

  if (id) {
    let res2 = await getDetail(id)
    res.json(new SuccessModel(res2))
  } else return new ErrorModel('获取博客详情失败,没有传入id')
})

// 编辑
router.post('/update', loginCheck, async function (req, res, next) {
  const id = req.query.id
  const data = req.body
  if (id && data.title) {
    let res2 = await updateBlog(id, data)
    if (res2) {
      res.json(new SuccessModel(res2))
    } else return new ErrorModel('更新博客失败')
  }
  return new ErrorModel('更新博客失败,没有传入id')
})

// 新增
router.post('/new', loginCheck, async function (req, res, next) {
  const bodyData = req.body
  bodyData.author = req.session.username
  bodyData.createtime = new Date().getTime()
  if (bodyData.title) {
    let data = await newBlog(bodyData)
    if (data) {
      res.json(new SuccessModel(data, '新建博客成功'))
      return
    }
    res.json(new ErrorModel(data, '新建博客失败'))
  } else return new ErrorModel('新建博客失败,没有传入数据')
})

// 删除
router.post('/del', loginCheck, async function (req, res, next) {
  const id = req.query.id
  if (id) {
    let res2 = await delBlog(id)
    if (res2) {
      res.json(new SuccessModel(res2, '删除成功'))
    } else return new ErrorModel('删除博客失败')
  }
  return new ErrorModel('删除博客失败,没有传入id')
})

module.exports = router
